package cn.rengy.web.framework.generate.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.rengy.lang.ResultEntity;
import cn.rengy.web.framework.generate.service.GenerateService;
import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.TemplateNotFoundException;


/**
 * 
 * 
 */
@Controller
@RequestMapping(value = "/authenticated/generate")
public class GenerateController {
	private static Logger logger = LoggerFactory.getLogger(GenerateController.class);
	@Autowired
	private GenerateService generateService;
	/**
	 * 预览
	 * @param pageid
	 * @return
	 */
	@RequestMapping("/view/{pageid}")
    public ModelAndView view(@PathVariable("pageid") Integer pageid){
        return generateService.generateView(pageid);
    }
	
	@RequestMapping(value="/page",method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<?> generate (HttpServletRequest request,@RequestBody Map<String,Object> paramMap) throws Exception{
		String path=request.getServletContext().getRealPath("/");
		generateService.generatePage(path, paramMap);
		return ResultEntity.ok();
	}
	@RequestMapping(value="/sql",method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<?> generateGridSql(@RequestBody Map<String,Object> paramMap){
		generateService.generateSql(paramMap);
		return ResultEntity.ok();
	}
	
	@RequestMapping(value="/constants",method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<?> generateConstants() throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException{
		generateService.generateConstants();
		return ResultEntity.ok();
	}
}
